package com.cy.service.news.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import com.cy.bean.news.News;
import com.cy.service.base.DAOSupport;
import com.cy.service.news.NewsService;
/**
 * 新闻Service接口实现类
 * @author CY
 *
 */
@Service
@Transactional
public class NewsServiceBean extends DAOSupport<News> implements NewsService,Pipeline {

	private int count = 0;
	
	private Spider spider;
	
	public Spider getSpider() {
		return spider;
	}

	public void setSpider(Spider spider) {
		this.spider = spider;
	}

	@Override
	public void process(ResultItems resultItems, Task task) {
		Map<String, Object> result = resultItems.getAll();
		News news = new News();
		news.setNews_title(result.get("title").toString());
		news.setNews_content(result.get("content").toString());
		news.setUrl(resultItems.getRequest().getUrl());
		try{
			save(news);
			count = 0;
		} catch(Exception e) {
			if(count > 10) {
				spider.stop();
				System.out.println("爬虫结束"+new Date());
			} else {
				count++;
			}
		}
	}

	@Override
	public News prev(Object value) {
		return prev("news_id", value);
	}

	@Override
	public News next(Object value) {
		return next("news_id",value);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<News> hotNews() {
		String jql = "select o from News o order by o.news_id desc";
		Query query = em.createQuery(jql);
		query.setFirstResult(0).setMaxResults(10);
		return query.getResultList();
	}

}
